package cn.virens.common.apifox.apifox.util;

import cn.virens.common.apifox.apifox.build.ApiFoxCollectionParam;
import cn.virens.common.apifox.apifox.build.ApiFoxCollectionParamItem;
import cn.virens.common.apifox.apifox.build.ApiFoxCollectionRequest;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.util.ObjUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Optional;

public class ApifoxUtil {
    /**
     * 处理请求实体对象
     */
    public static ApiFoxCollectionRequest request(Class<?> clazz, Method method, ApiFoxCollectionRequest request) {
        return Optional.ofNullable(request).or(ApifoxUtil::newRequest).map(temp -> {
            temp.setJsonSchema(ApifoxUtilBody.getRequest(clazz, method));

            if (ObjUtil.isNotEmpty(temp.getJsonSchema())) {
                temp.setType("application/json");
            } else {
                temp.setType("none");
            }

            return temp;
        }).orElse(null);
    }

    /**
     * 处理注解请求参数
     */
    public static ApiFoxCollectionParam param0(Class<?> clazz, Method method, ApiFoxCollectionParam param) {
        return Optional.ofNullable(param).or(ApifoxUtil::newParam).map(temp -> {
            if (temp.getQuery() == null || temp.getQuery().isEmpty()) {
                temp.setQuery(new ArrayList<>());
            }

            return param1(method, temp);
        }).get();
    }

    /**
     * 获取方法参数中RequestParam注解对应的参数
     */
    private static ApiFoxCollectionParam param1(Method method, ApiFoxCollectionParam temp) {
        for (ApiFoxCollectionParamItem item : ApifoxUtilParam.getParamItem(method)) {
            if (!CollUtil.contains(temp.getQuery(), a -> a.equals(item))) {
                temp.getQuery().add(item);
            }
        }

        return temp;
    }

    private static Optional<ApiFoxCollectionRequest> newRequest() {
        return Optional.of(new ApiFoxCollectionRequest());
    }

    private static Optional<ApiFoxCollectionParam> newParam() {
        return Optional.of(new ApiFoxCollectionParam());
    }

}
